package idv.nightpig.lab05.protocol;

import idv.nightpig.lab05.protocol.annotation.Protocol;

import java.lang.annotation.Annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

@Component
public class Lab05ProtocolBeanPostProcessor implements BeanPostProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(Lab05ProtocolBeanPostProcessor.class);
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Lab05ProtocolManager) {
            Lab05ProtocolManager pm = (Lab05ProtocolManager) bean;
            for (String s : webApplicationContext.getBeanDefinitionNames()) {
                Object b = webApplicationContext.getBean(s);
                if (b instanceof Lab05Protocol) {
                    for (Annotation a : b.getClass().getDeclaredAnnotations()) {
                        if (a instanceof Protocol) {
                            Protocol p = (Protocol) a;
                            for (String v : p.version()) {
                                String key = p.value() + "@" + v;
                                pm.getProtocols().put(key, s);
                                LOGGER.info("{} {}", key, s);
                            }
                        }
                    }
                }
            }
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

}
